/*
 * Project it.battlehorse.rcp.tools.log
 * Created on Nov 19, 2005
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * A copy of the LGPL is available also at
 * http://www.gnu.org/copyleft/lesser.html
 * 
 */ 
package it.battlehorse.rcp.tools.log;

import it.battlehorse.rcp.tools.log.internal.Logger;
import it.battlehorse.rcp.tools.log.views.ActorLogView;

import java.util.ArrayList;
import java.util.List;

/**
 * Collects all the logging requests and generate the events which are used to
 * update the {@link ActorLogView }. This class implements the singleton pattern
 * and the shared instance must be retrieved from the ServiceLocator framework.
 * 
 * @author battlehorse
 * @since Nov 19, 2005
 */
public class LogCollector {

	/**
	 * Contains the shared instance of the log collector
	 */
	private static LogCollector instance;
	
	/**
	 * The list of registered listeners
	 */
	private List<ILogListener> listenersList;
		
	
	/**
	 * Returns the shared instance of the class. This method should not be invoked
	 * directly : the log collector should be accessed using the Inversion of Control Service Locator framework.
	 * 
	 * @return the shared actor registry instance
	 */
	public static synchronized LogCollector getInstance() {
		if (instance == null)
			instance =  new LogCollector();
		
		return instance;
	}
		 
	private LogCollector() {
		listenersList = new ArrayList<ILogListener>();		
		
		// Registers Logger as the default log implementation
		System.setProperty("org.apache.commons.logging.Log", Logger.class.getName());		
	}
	
	/**
	 * Adds a listener which is notified on logging events
	 * 
	 * @param listener  a listener which is notified on logging events
	 */
	public void addLogListener(ILogListener listener) {				
			listenersList.add(listener);
	}

	/**
	 * Notifies the registered listeners
	 * @param event
	 */
	public void notifyLogListeners(ILoggable loggable) {
			for (ILogListener listener  : listenersList) {
				listener.logOccurred(loggable);
			}
	}

	/**
	 * Removes a listener from notification on logging events
	 * 
	 * @param listener the listener to be removed
	 */
	public void removeLogListener(ILogListener listener) {
			listenersList.remove(listener);
	}
}
